﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Soft.Net
{
    [TypeConverter(typeof(TcpConnectIpAddressTypeConverter))]
    [Serializable]
    public struct TcpConnectIpAddress : IEquatable<TcpConnectIpAddress>
    {
        public IP IpAddress
        {
            get
            {
                return this.mIpAddress;
            }
            set
            {
                if (this.mIpAddress != value)
                {
                    this.mIpAddress = value;
                }
            }
        }


        public ushort Port
        {
            get
            {
                return this.mPort;
            }
            set
            {
                if (this.mPort != value)
                {
                    this.mPort = value;
                }
            }
        }

        public override bool Equals(object obj)
        {
            return obj != null && obj is TcpConnectIpAddress && this.Equals((TcpConnectIpAddress)obj);
        }

        public override int GetHashCode()
        {
            return this.mIpAddress.Text.GetHashCode() ^ this.mPort.GetHashCode();
        }

        public override string ToString()
        {
            return string.Format("{0}:{1}", this.mIpAddress.Text, this.mPort);
        }

        public static TcpConnectIpAddress Parse(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentNullException(value);
            }
            TcpConnectIpAddress result = default(TcpConnectIpAddress);
            value = value.Trim();
            if (ToolsClass.RegexTest("^\\d{1,3}(\\.\\d{1,3}){3}:\\d{1,5}$", value))
            {
                string[] array = value.Split(new char[]
                {
                    ':'
                }, StringSplitOptions.RemoveEmptyEntries);
                result.mIpAddress = (IP)array[0];
                result.mPort = (byte)array[1].ConvertTo(0, true);
                return result;
            }
            throw new FormatException("参数 value 表示的地址格式有错误");
        }

        public bool Equals(TcpConnectIpAddress other)
        {
            return this.mIpAddress == other.mIpAddress && this.mPort == other.mPort;
        }

        public static explicit operator TcpConnectIpAddress(string value)
        {
            return TcpConnectIpAddress.Parse(value);
        }

        public static bool operator ==(TcpConnectIpAddress a, TcpConnectIpAddress b)
        {
            return a.Equals(b);
        }

        public static bool operator !=(TcpConnectIpAddress a, TcpConnectIpAddress b)
        {
            return !a.Equals(b);
        }

        private IP mIpAddress;

        private ushort mPort;

        public static readonly TcpConnectIpAddress Empty = new TcpConnectIpAddress
        {
            mIpAddress = IP.Empty,
            mPort = 0
        };
    }
}
